package bar.dark.lee.fan;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;

public class FanFriendActivity extends SuperActivity
{
	/** 다이얼로그에 선택될 전화번호 데이터 키 값 */
	public static final String FAN_TEL = "TEL";
	/** 다이얼로그에 선택될 이름 데이터 키 값 */
	public static final String FAN_NAME = "NAME";
	/** 직접 입력 or 주소록 선택 입력 */
	public static final String INPUT_TYPE = "input_type";
	public static final int DIRECT = 1;
	public static final int FRIEND = 2;
	
	
	private String name = null;
	private String tel = null;
	
	private ArrayList<TelData> telList = new ArrayList<TelData>();
	private ArrayList<TelData> totalList = new ArrayList<TelData>();
	private String [] listData;
	
	/** 데이터가 없을시 나오는 뷰 */
	private View resultView;
	
	/** 직접 입력 뷰 */
	private View directView;
	
	/** 검색 입력 창 */
	private AutoCompleteTextView autoEditText;
	
	/** 검색 버튼 */
	private Button searchButton;
	
	/** */
	private ListView listView;
	
	private int firstFlag = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.fan_tel_activity);
		
		setGoneTipButton();
		setTitle("친구목록");
		
		firstFlag = 0;
		
		Intent intent = getIntent();
		name = intent.getStringExtra(FAN_NAME);
		tel = intent.getStringExtra(FAN_TEL);
		
		if (name == null)
		{
			name = "";
		}
		 
		if (tel == null)
		{
			tel = "";
		}
		
		setFindView();
		setOnClickListener();
		setData(null);
	}

	private void setFindView()
	{
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		TextView tv = (TextView) resultView.findViewById(R.id.textViewNoResult);
		tv.setText("친구가 없습니다. ㅜ.ㅜ");
		
		directView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		TextView tv2 = (TextView) directView.findViewById(R.id.textViewNoResult);
		tv2.setText("직접 입력");
		
		listView = (ListView) findViewById(R.id.fanTelListView);
		
		autoEditText = (AutoCompleteTextView) findViewById(R.id.fanTelAutoEditText);
		searchButton = (Button) findViewById(R.id.fanTelSearchButton);
	}

	private void setData(String name)
	{
		if (listView.getHeaderViewsCount() > 0)
		{
//			listView.removeHeaderView(resultView);
			listView.removeHeaderView(directView);
		}
		
		listView.setHeaderDividersEnabled(true);
		
		telList = getTelData(name);
		autoEditText.setAdapter(null);
		listView.setAdapter(null);
		
		if (telList.size() < 1)
		{
			if (listView.getHeaderViewsCount() > 0)
			{
//				listView.removeHeaderView(resultView);
				listView.removeHeaderView(directView);
			}
			
			listView.addHeaderView(directView);
//			listView.addHeaderView(resultView);
			listView.setHeaderDividersEnabled(false);
//			listView.setOnItemClickListener(null);
			listView.setOnItemClickListener(onItemClickListener);
			
			BDUtil.showToast(this, "친구 목록을 가져 올수 없거나, 친구가 없습니다.");
		}
		else
		{
			listView.addHeaderView(directView);
			
			if (name == null)
			{
				totalList.addAll(telList);
			}
			
			listView.setOnItemClickListener(onItemClickListener);
		}
		
		listData = new String[totalList.size()];
		
		for (int i = 0; i < totalList.size(); i++)
		{
			listData[i] = totalList.get(i).getName();
		}
		
		// 몇 글자 부터 작동 시킬지 여부
		autoEditText.setThreshold(1);
		
		ArrayAdapter<String> autoAdapter = 
				new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData);
		
		autoEditText.setAdapter(autoAdapter);
		
		TelAdapter adapter = new TelAdapter(this, R.layout.fan_tel_list_item, telList);
		listView.setAdapter(adapter);
	}
	
	private void setOnClickListener()
	{
		searchButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setData(autoEditText.getText().toString());
			}
		});
	}
	
	/**
	 * 전화번호부를 가져오기
	 * @return Cursor
	 */
	private ArrayList<TelData> getTelData(String name)
	{
		ArrayList<TelData> list = new ArrayList<TelData>();
		Cursor c = null;
		
		try
		{
			Uri uri = Phone.CONTENT_URI;

			String [] projection = new String[]{
					Phone._ID, Phone.DISPLAY_NAME, Phone.DATA};
			
			String selection = null;
			String [] selectionArgs = null;
			
			if (name != null)
			{
				// 쿼리 날려서 커서 얻기  
				selection = Phone.DISPLAY_NAME + " like ?";
				selectionArgs = new String[]{name + "%%"};  
			}

			String sortOrder = Phone._ID + " COLLATE LOCALIZED ASC";  
			
			c = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
			
			c.moveToFirst();
			
			for (int i = 0; i < c.getCount(); i++)
			{
				TelData data = new TelData();
				
				data.setId(c.getInt(0) + "");
				data.setName(c.getString(1));
//				data.setTel(c.getString(2));
				
				String tel = c.getString(2);
				
				try
				{
					tel = tel.replace("-", "");
					
					StringBuffer telStr = new StringBuffer(tel);
					
					if (tel.length() == 11)
					{
						telStr = telStr.insert(3, "-");
						telStr = telStr.insert(8, "-");
						
						data.setTel(telStr.toString());
					}
					else if (tel.length() == 10)
					{
						telStr = telStr.insert(3, "-");
						telStr = telStr.insert(7, "-");
						
						data.setTel(telStr.toString());
					}
					else
					{
						data.setTel(tel);
					}
				} catch (Exception e)
				{
					data.setTel(tel);
				}
				
				list.add(data);
				
				c.moveToNext();
			}
			
		} catch (Exception e)
		{
			e.printStackTrace();
			return list;
		} finally {
			if (c != null)
			{
				c.close();
			}
		}
		
		return list;
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			if (position == 0) {
				Intent intent = new Intent();
				intent.putExtra(INPUT_TYPE, DIRECT);
				intent.putExtra(FAN_NAME, "");
				intent.putExtra(FAN_TEL, "");
				setResult(Activity.RESULT_OK, intent);
				
				finish();
			} else {
				TelData data = telList.get(position-1);
				
				Intent intent = new Intent();
				intent.putExtra(INPUT_TYPE, FRIEND);
				intent.putExtra(FAN_NAME, data.getName());
				intent.putExtra(FAN_TEL, data.getTel());
				setResult(Activity.RESULT_OK, intent);
				finish();
			}
		}
	};
	
	private class TelAdapter extends ArrayAdapter<TelData>
	{
		public TelAdapter(Context context, int textViewResourceId,
				ArrayList<TelData> list)
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.fan_tel_list_item, null);
			}
			
			TelData data = telList.get(position);
			
			TextView nameText = (TextView) v.findViewById(R.id.fanRadioName);
			TextView telText = (TextView) v.findViewById(R.id.fanRadioTel);
			RadioButton rb = (RadioButton) v.findViewById(R.id.fanTelRadioButton);
			
			nameText.setText(data.getName());
			telText.setText(data.getTel());
			
			if (data.getTel() != null)
			{
				if (data.getTel().equals(tel))
				{
					rb.setChecked(true);
				}
				else
				{
					rb.setChecked(false);
				}
			}
			
			return v;
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
